<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\StockReward;
class StockOrder extends Model
{   
    protected $table = 'stock_orders';
    //
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'stock_activity_id',
        'user_id',
        'money',
        'pay_money',
        'stock_name',
        'stock_code',
        'open_price',
        'close_price',
        'yield',
        'out_trade_no',
        'transaction_id',
        'payment_time',
        'status',
        'rate'
    ];

    public function status(){
        $status = ['未支付','已支付','已作废'];
        return $status[$this->status];
    }

    public function statuslabel(){
        $status = ['label-primary ','label-success','label-danger'];
        return $status[$this->status];
    }

   
    protected function find_activity($uid)
    {
        $order=$this->where(['user_id'=>$uid])->paginate(8);
        foreach($order as $key=>$value){
            $activity=StockActivity::find($value->stock_activity_id);
            $order[$key]->order=$activity;
        }
        return $order;
    }

    public function activity()
    {
        return $this->hasOne('App\Models\StockActivity','id','stock_activity_id');
    }

    public static function find_sort($id)
    {
        $data=self::where(['stock_activity_id'=>$id])->orderby('yield','desc')->get();
        return $data;
    }

    /*
     * 查询某个活动的所以订单
     * $id活动的id
     * */

    public static function find_activity_order($id)
    {
        $data=self::where('stock_orders.stock_activity_id',$id)->join('users','users.id','=','stock_orders.user_id')->get();
        return $data;
    }

    public static function add_data($data)
    {
        $order_id=self::insertGetId($data);
        return $order_id;
    }

    public static function find_by_id($id)
    {
        return self::find($id);
    }
    
    public function user(){
        return $this->belongsTo('App\User');
    }
    
    public static function update_order($id,$data)
    {
        return self::where('id',$id)->update($data);
    }

    public function reward(){
        $info = StockReward::where('stock_activity_id','=',$this->stock_activity_id)
                    ->where('stock_order_id','=',$this->id)->first();
        return $info;
    }

    public function hasReward(){
        return $this->hasOne('App\Models\StockReward','stock_order_id');
        
    }

}
